let _baseUrl=getApp().globalData.baseUrl;
const request=function(type, url, obj, msg){
	let token = uni.getStorageSync('token') || '';
	let pro = new Promise((resolve, reject) => {
		if (msg) {
			uni.showLoading({
				title: '请求中,请稍等..',
				mask:true
			});
		}
		uni.request({
			url: _baseUrl +'api/'+url,
			data: obj,
			method: type,
			header: {
				'token':token,
				'x-requested-with':'XMLHttpRequest'
			},
			dataType: 'json',
			success: (res) => {
				if (msg) {
					uni.hideLoading();
				}
				if (res.statusCode == 200) {
					if (res.data.code == 1) {
						if (msg && res.data.msg) {
							setTimeout(function() {
								uni.showToast({
									title: res.data.msg,
									icon: 'none'
								});
							}, 500);
						}
						resolve(res.data.data);	
					}
					if (res.data.code == 0) {
						if (msg && res.data.msg) {
							setTimeout(function() {
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration:2000
								});
							}, 500);
						}
						reject(res.data);
					}
				}
				if (res.statusCode == 401) {
					uni.setStorageSync('token','');
					uni.setStorageSync('userinfo','');
					uni.showModal({
						title:'登陆提示',
						content:'你还没有登陆，点击确定跳转到登陆页面！',
						success:function(res){
							if(res.confirm){
								let pages = getCurrentPages();
								let currentpage = pages[pages.length - 1];
								let redict_url=currentpage.$page.fullPath;								
								uni.setStorageSync('redict_url',redict_url);
								// #ifdef MP-WEIXIN
								uni.navigateTo({
									url:'/pages/index/login'
								});
								// #endif
								// #ifdef H5
								location.href=base+'api/mpwechat/connect?action=100';
								// #endif
							}
						}
					});
				}
				if (res.statusCode == 500) {
					setTimeout(function() {
						uni.showToast({
							title: '系统错误',
							icon: 'none'
						});
					}, 500);
				}
			},
			fail: (res) => {
				if (msg) {
					uni.hideLoading();
				}
				setTimeout(function() {
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
				}, 500);
				reject();
			}
		});
	});
	return pro;
}
const post = function(url, obj, msg = false){
	return request("POST", url, obj, msg)
}
const get = function(url, obj, msg = false){
	return request("GET", url, obj, msg)
}
const uploadFile=function(file,successCallback) {
    let uri = "api/common/upload" ;
	let token = uni.getStorageSync('token') || '';
    uni.showLoading({
		title: '图片上传中..'
    });
    uni.uploadFile({
      url: _baseUrl + uri,
      filePath: file,
	  header:{
		  'token':token,
		  'x-requested-with':'XMLHttpRequest'
	  },
      name: 'file',
      success: function(uploadRes) {
        if (uploadRes.statusCode === 200) {
          let res = JSON.parse(uploadRes.data);
          if (res.code == 1) {
             successCallback(res.data);
          } else {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        } else {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
		uni.hideLoading();
      },
	  fail:function(e){
		  console.log(e);
		  uni.hideLoading();
	  }
    });
}
const userinfo=function(key){
	let userinfo=uni.getStorageSync('userinfo') || '';
	if(key){
		if(value){
			userinfo[key]=value;
			uni.setStorageSync('userinfo',userinfo);
		}
		return userinfo[key] || '';
	}
	return userinfo;
}
const customer=function(key,value=''){
	let customer=uni.getStorageSync('customer') || '';
	if(key){
		if(value){
			customer[key]=value;
			uni.setStorageSync('customer',customer);
		}
		return customer[key] || '';
	}
	return customer;
}
const navigateTo=function(e){
	if(typeof e=='object'){
		e='/pages/'+e.currentTarget.dataset.url;
	}else{
		e='/pages/'+e;
	}
	uni.navigateTo({
		url:e,
		fail:function(res){
			console.log(res);
		}
	});
}
const reLaunch=function(e){
	if(typeof e=='object'){
		e='/pages/'+e.currentTarget.dataset.url;
	}else{
		e='/pages/'+e;
	}
	uni.reLaunch({
		url:e,
		fail:function(res){
			console.log(res);
		}
	});
}
const redirectTo=function(e){
	if(typeof e=='object'){
		e='/pages/'+e.currentTarget.dataset.url;
	}else{
		e='/pages/'+e;
	}
	uni.redirectTo({
		url:e,
		fail:function(res){
			console.log(res);
		}
	});
}
const switchTab=function(e){
	if(typeof e=='object'){
		e='/pages/'+e.currentTarget.dataset.url;
	}else{
		e='/pages/'+e;
	}
	uni.switchTab({
		url:e,
		fail:function(res){
			console.log(res);
		}
	});
}
const navigateBack=function(timeout=0,refresh=false){
	setTimeout(res=>{
		uni.navigateBack({
			success: function () {
				let currPages = getCurrentPages();
				if(refresh){
					wx.redirectTo({
						url: "/" + currPages[currPages.length - 1].route				
					});		
				}				
			}					
		});
	},timeout);
}
const msg=function(title, duration=3000, mask=false, icon='none'){
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
const validate=function(name,formdata=''){
	let val;
	if(formdata){
		val=formdata[name];
	}else{
		val=this.formdata[name];
	}
	let rules=this.rules[name].rule;
	let title=this.rules[name].title;
	let attributes=rules.split(';');
	let allowempty=true;
	for(let ix=0;ix<attributes.length;ix++){
		let attribute=attributes[ix];
		if(attribute=="require"){
			allowempty=false;
			break;
		}
	}
	if(!allowempty && val===''){
		this.rules[name].error=title+'不能为空';
		return false;
	}
	if(!allowempty && val instanceof Array && val.length===0){
		this.rules[name].error=title+'不能为空';
		return false;
	}
	if(allowempty && (val==='' || val===null || val===0)){
		this.rules[name].error='';
		return true;
	}
	for(let ix=0;ix<attributes.length;ix++){
		let attribute=attributes[ix];
		if(attribute=="require"){
			continue;
		}
		if(attribute=='number' && isNaN(val)){
			this.rules[name].error=title+"必须为数字";
			return false;
		}
		let reglen = /length\(\d*~\d*\)/;
		if(reglen.test(attribute)){
			let d=attribute.substr(7);
			let drr=d.substr(0,d.length-1).split('~');
			if(drr[0] && val.length<parseInt(drr[0])){
				this.rules[name].error=title+"长度不能小于"+drr[0];
				return false;
			}
			if(drr[1] && val.length>parseInt(drr[1])){
				this.rules[name].error=title+"长度不能大于"+drr[1];
				return false;
			}
		}
		let regblen = /length\(\d*\)/;
		if(regblen.test(attribute)){
			let d=parseInt(attribute.slice(7,attribute.indexOf(')')));
			if(val.length!=d){
				this.rules[name].error=title+"长度为必须"+d+"位";
				return false;
			}	
		}
		let rang=/range\(\d*~\d*\)/;
		if(rang.test(attribute)){
			let d=attribute.substr(6);
			let drr=d.substr(0,d.length-1).split('~');
			if(drr[0] && Number(val)<parseInt(drr[0])){
				this.rules[name].error=title+"不能小于"+drr[0];
				return false;
			}
			if(drr[1] && Number(val)>parseInt(drr[1])){
				this.rules[name].error=title+"不能大于"+drr[1];
				return false;
			}
		}
		if(attribute=='integer'){
			let reg1 =/^[-+]?\d*$/;	
			if(!reg1.test(val)){
				this.rules[name].error=title+"必须为整数";
				return false;
			}		
		}
		if(attribute=='+integer'){
			let reg1 =  /^\d+$/;
			if(!reg1.test(val)){
				this.rules[name].error=title+"必须为大于0的整数";
				return false;
			}
		}
		if(attribute=='chinaChar'){
			for(let i=0;i<val.length;i++){
				let s=val.charAt(i);
				let reg1 = /[\u4e00-\u9fa5]{1}/;  			
				if(!reg1.test(s)){
					this.rules[name].error=title+"必须是中文";
					return false;
				}					
			}	
		}
		if(attribute=='unchinaChar'){
			for(let i=0;i<val.length;i++){
				let s=val.charAt(i);
				let reg1 = /[\u4e00-\u9fa5]{1}/;  			
				if(reg1.test(s)){
					this.rules[name].error=title+"不能包含中文";
					return false;
				}					
			}	
		}
		if(attribute=='unNum' && !isNaN(val)){
			this.rules[name].error=title+"不能为数字";
			return false;
		}
		if(attribute=='email'){	
			let szReg=/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org|info|cc|tv)$/; 
			let c=szReg.test(val); 
			if(!c){
				this.rules[name].error=title+"格式不正确";
				return false;
			}	
		}
		if(attribute=='mobile'){
			let reg = /^1[3|4|5|6|7|8][0-9]{9}$/; 
			let flag = reg.test(val);
			if(!flag){
				this.rules[name].error=title+"格式不正确";
				return false;
			}	
		}	
	}	
	this.rules[name].error='';
	return true;
}

export const baseUrl=_baseUrl;
export const methods={
	$get:get,
	$post:post,
	$validate:validate,
	$userinfo:userinfo,
	$customer:customer,
	$uploadFile:uploadFile,
	$navigateTo:navigateTo,
	$reLaunch:reLaunch,
	$redirectTo:redirectTo,
	$switchTab:switchTab,
	$navigateBack:navigateBack,
	$msg:msg
}